import {fileURLToPath, URL} from 'node:url'
import {loadEnv} from 'vite'
import vue from '@vitejs/plugin-vue'
import vueDevTools from 'vite-plugin-vue-devtools'
import tailwindcss from '@tailwindcss/vite'
import {ViteEjsPlugin} from 'vite-plugin-ejs'
import type {UserConfig, ConfigEnv} from 'vite'
import {viteMockServe} from 'vite-plugin-mock'

const root = process.cwd()
// https://vite.dev/config/
export default ({command, mode}: ConfigEnv): UserConfig => {

  const isBuild = command === 'build';
  let actualMode = mode;
  if (!actualMode) {
    actualMode = isBuild ? 'production' : 'development';
  }
  const env = loadEnv(actualMode, root);

  return {

    base: env.VITE_BASE_PATH,
    plugins: [
      vue(),
      vueDevTools(),
      tailwindcss(),
      ViteEjsPlugin({
        title: env.VITE_APP_TITLE
      }),
      viteMockServe({
        mockPath: 'mock', // mock 文件目录
        enable: command === 'serve', // 只在开发环境启用
        ignore: /^\_/, // 忽略以 _ 开头的文件
        logger: true, // 启用日志
      })
    ],
    build: {
      target: 'es2015',
      outDir: env.VITE_OUT_DIR || 'dist',
    },
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url))
      },
    },
    // 生产环境下清除 console 和debugger
    esbuild: {
      pure: env.VITE_DROP_CONSOLE === 'true' ? ['console.log'] : undefined,
      drop: env.VITE_DROP_DEBUGGER === 'true' ? ['debugger'] : undefined
    },
    server: {
      port: 8000,
      proxy: {
        //Proxy代理 开发中常用的解决跨域问题的方案
        //target: 代理目标地址  changeOrigin: 修改请求头中的host为目标URL  rewrite: 路径重写
        '/api': {
          target: 'http://127.0.0.1:8000',
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, '')
        }
      },
    }
  }
}
